package com.pets.controller;


import com.pets.entity.Users;
import com.pets.service.IUsersService;
import com.pets.utils.Result;
import com.pets.viewModels.UsersViewModels;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 啦啦啦
 * @since 2024-04-09
 */
@RestController
@RequestMapping("/users")
@Api(tags = "用户表接口")
public class UsersController {

    @Autowired
    private IUsersService usersService;

    @Autowired
    public RedisTemplate<String, String> redisTemplate;

    //@Autowired
    //private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}") //从application.yml中读取配置
    private String uploadDirectory;

    //是否开启qq验证码验证
    private String isCode = "1";

    @ApiOperation("获取验证码")
    @GetMapping("/verificationkode")
    public Result GetVerificationkode(@RequestParam String username) {
        if(!isCode.equals("1")){
            return Result.fail("未开启验证码模式！");
        }
        int length = 4;//设置验证长度
        Set<Integer> uniqueNumbers = new HashSet<>();
        Random random = new Random();
        while (uniqueNumbers.size() < length) {
            int number = random.nextInt(10); // 生成0到9之间的随机数
            uniqueNumbers.add(number);
        }
        StringBuilder codeBuilder = new StringBuilder();
        for (int number : uniqueNumbers) {
            codeBuilder.append(number);
        }
        redisTemplate.opsForValue().set(username,codeBuilder.toString(),5, TimeUnit.MINUTES);
        String value = redisTemplate.opsForValue().get(codeBuilder.toString());
        System.out.println(value);
        /*//发邮件
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人邮件地址
        message.setFrom(uploadDirectory);
        //要发送的qq邮箱(收件人地址)
        message.setTo(username);
        //邮件主题
        message.setSubject("你的验证码是");
        //邮件正文
        message.setText(codeBuilder.toString());
        avaMailSender.send(message);*/
        return Result.success("",codeBuilder.toString());
    }


    @ApiOperation("用户登陆")
    @GetMapping
    public Result login(@RequestParam String username, @RequestParam String password, HttpSession session) {
        return usersService.login(username, password,session);
    }

    @ApiOperation("退出登陆")
    @PostMapping("/loginout")
    public Result loginout(HttpSession session) {
        session.removeAttribute("user");
        return Result.success("退出成功！");
    }

    @ApiOperation("用户注册（电话，邮箱，账号这三个选填，密码是必须填，是否设置管理员，头像设置，这些参数）")
    @PostMapping
    public Result register(@RequestBody UsersViewModels users) {
        if (isCode.equals("1") && users.getIsCode() != null && users.getIsCode() && users.getMailbox() != null && !users.getMailbox().isEmpty()) {
            if (users.getCode().isEmpty()) {
                return Result.fail("验证码不能为空");
            }
            String value = redisTemplate.opsForValue().get(users.getMailbox());
            System.out.println("验证码：" + value);
            if (value == null || value.isEmpty()) {
                System.out.println("过期");
                return Result.fail("验证码过期");
            }
            if (!users.getCode().equals(value)) {
                System.out.println("错误");
                return Result.fail("验证码错误");
            }
        }
        return usersService.register(users);
    }

    @ApiOperation("根据id删除用户")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id,HttpSession session) {
        /*Object userObject = session.getAttribute("users");
        if (userObject instanceof Users) {
            Users user = (Users) userObject;
            System.out.println(user.getUsername()+"/"+user.getUserId());
            if (!user.getIsAdministrators()){
                return Result.fail("您不是管理员！");
            }
        }else {
            return Result.fail("未登录！");
        }*/
        return usersService.deleteById(id);
    }


    @ApiOperation("修改用户")
    @PutMapping("/update")
    public Result update(@RequestBody Users users) {
        return usersService.updateData(users);
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("/get/{id}")
    public Result get(@PathVariable Integer id) {
        return usersService.selectById(id);
    }

    @ApiOperation("分页查询用户")
    @GetMapping("/list")
    public Result listPage(@ApiParam(value = "页码", required = true)@RequestParam(defaultValue = "1") Integer page,
                           @ApiParam(value = "页数", required = true)@RequestParam(defaultValue = "10") Integer pageSize,
                           @ApiParam(value = "账号搜索")@RequestParam(required = false) String username,
                           @ApiParam(value = "昵称搜索")@RequestParam(required = false) String nickname,
                           @ApiParam(value = "邮箱搜索")@RequestParam(required = false) String mailbox,
                           @ApiParam(value = "电话搜索")@RequestParam(required = false) String phone,
                           @ApiParam(value = "是否禁用搜索")@RequestParam(required = false) Boolean isDisable) {
        return usersService.selectPage(page, pageSize, username, nickname, mailbox,phone,isDisable);
    }
}
